package com.yaxin.web.controller.outsourcing;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.lang.tree.Tree;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yaxin.common.core.domain.PageQuery;
import com.yaxin.common.core.domain.R;
import com.yaxin.common.core.domain.entity.SysDept;
import com.yaxin.common.core.page.TableDataInfo;
import com.yaxin.outsourcing.R.Result;
import com.yaxin.outsourcing.domain.po.AccessApplication;
import com.yaxin.outsourcing.domain.po.OutsourcingPerson;
import com.yaxin.outsourcing.domain.vo.AccessApplicationApprovalVO;
import com.yaxin.outsourcing.domain.dto.AccessApplicationDTO;
import com.yaxin.outsourcing.service.IAccessApplicationService;
import com.yaxin.system.service.ISysDeptService;
//import com.yaxin.system.service.impl.WorkProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 临时通行证申请单表 前端控制器
 * </p>
 *
 * @author zcc
 * @since 2025-07-29
 */
@Slf4j
@SaIgnore
@RestController
@RequestMapping("/api/apply")
public class AccessApplicationController {

    @Autowired
    private IAccessApplicationService accessApplicationService;
    @Autowired
    private  ISysDeptService deptService;
//    @Autowired
//    private WorkProcessService workProcessService;
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 临时通行证申请表查询
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo<AccessApplication> appList(AccessApplication accessApplication, PageQuery pageQuery){
        accessApplicationService.sendMqMessage("20250701001");
        return accessApplicationService.appList(accessApplication, pageQuery);
    }

    /**
     * 新增申请单
     * @return
     */
    @PostMapping
    public Result<Integer> create(@Valid @RequestBody AccessApplicationDTO dto) {
        return Result.success(accessApplicationService.createApplication(dto));
    }

    /**
     * 修改申请单
     * @return
     */
    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id,
                               @Valid @RequestBody AccessApplicationDTO dto) {
        accessApplicationService.updateApplication(id, dto);
        return Result.success();
    }

    /**
     * 更新申请单状态
     * @return
     */
    @PutMapping("/{id}/status/{status}")
    public Result<Void> updateStatus(
        @PathVariable Long id,
        @PathVariable Integer status
    ) {
        accessApplicationService.updateStatus(id, status);
        return Result.success();
    }

    @PutMapping("/status/{status}")
    public Result<Void> updateStatusBatch(
        @RequestBody List<Long> ids,   // JSON 数组接收
        @PathVariable Integer status
    ) {
        ids.forEach(id -> accessApplicationService.updateStatus(id, status));
        return Result.success();
    }



    /**
     * 删除申请单
     * @return
     */
    @DeleteMapping
    public Result<Void> batchDelete(@RequestBody List<Long> ids) {
        accessApplicationService.deleteApplication(ids);
        return Result.success();
    }

    /**
     * 获取申请单详情
     */
    @GetMapping("/{id}")
    public Result<AccessApplication> getDetail(@PathVariable Long id) {
        AccessApplication accessApplication = accessApplicationService.getById(id);
        return Result.success(accessApplication);
    }

    /**
     * 获取申请单详情
     */
    @GetMapping("/ApplyAndPerson/{id}")
    public Result<AccessApplicationApprovalVO> getApplyAndPerson(@PathVariable Long id) {
        AccessApplication accessApplication = accessApplicationService.getById(id);
        List<OutsourcingPerson> personList = accessApplicationService.getPersonListByAppId(id);
        for(OutsourcingPerson person : personList){
            String company = accessApplicationService.getById(person.getAppId()).getOutUnit();
            String area = accessApplicationService.getById(person.getAppId()).getArea();
            String appNo = accessApplicationService.getById(person.getAppId()).getAppNo();
            person.setCompanyName(company);
            person.setWorkArea(area);
            person.setAppNo(appNo);
        }
        AccessApplicationApprovalVO vo = new AccessApplicationApprovalVO();
        BeanUtils.copyProperties(accessApplication,vo);
        vo.setDatatemplate(personList);
        return Result.success(vo);
    }

    /**
     * 导出申请单数据
     * @param response
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response) {
//        Page<AccessApplicationVO> page = accessApplicationService.appList(null,null,null,null,null,null,null,1,1000);
//        List<AccessApplicationVO> list = page.getRecords();
//        for (AccessApplicationVO vo : list) {
//            System.out.println("状态:"+vo.getStatus());
//        }
//        ExcelUtil.exportExcel(list, "申请单", AccessApplicationVO.class, response);
    }


    /**
     * 生成申请单编号
     * @return
     */
    @GetMapping("/generateAppNo")
    public Result<String> generateApplicationNo() {
        return Result.success(accessApplicationService.generateApplicationNo());
    }



    /**
     * 获取部门树列表
     */
    @GetMapping("/deptTree")
    public R<List<Tree<Long>>> deptTree(SysDept dept) {
        return R.ok(deptService.selectDeptTreeListWithoutOutSourcing(dept));
    }


    /**
     * 根据部门ID查询部门名称
     */
    @GetMapping("/deptName/{deptId}")
    public R<String> getDeptName(@PathVariable Long deptId) {
        SysDept dept = deptService.selectDeptById(deptId);
        return R.ok(dept.getDeptName());
    }

    /**
     * 批量/单个送审OA
     */
    /**
    @PostMapping("/sendOaToApproval")
    public R<Void> sendOA(@RequestBody List<Long> ids) {
        ids.forEach(id -> {
            try {
                Result<AccessApplicationApprovalVO> applyAndPerson = getApplyAndPerson(id);
                String processFlag = "ded14cb9-c32c-4b7e-b1c3-a8aef92c0be4";

                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("latest", false);
                requestBody.put("title", "外包人员入场申请");
                requestBody.put("identity", "申请人身份");
                requestBody.put("data", applyAndPerson.getData());
                requestBody.put("parentWork", null);
                requestBody.put("allowEdition", false);
                requestBody.put("skipDraftCheck", false);
                requestBody.put("process","ee0f3606-04dc-42a9-b480-b42d1ed81e2e");

                String requestBodyString = objectMapper.writeValueAsString(requestBody);
                ResponseEntity<String> response = workProcessService.createWorkProcess(processFlag, requestBodyString);

                // 解析响应 + 自动处理任务
                if (response.getStatusCode() == HttpStatus.OK) {
                    Map<String, Object> responseMap = objectMapper.readValue(response.getBody(), Map.class);
                    if ("success".equals(responseMap.get("type"))) {
                        List<Map<String, Object>> dataList = (List<Map<String, Object>>) responseMap.get("data");
                        if (dataList != null && !dataList.isEmpty()) {
                            List<Map<String, Object>> taskList = (List<Map<String, Object>>) dataList.get(0).get("taskList");
                            if (taskList != null && !taskList.isEmpty()) {
                                String taskId = (String) taskList.get(0).get("id");
                                workProcessService.taskProcessing(taskId);
                            }
                        }
                    }
                } else {
                    log.warn("ID={} 送审失败: {}", id, response.getStatusCode());
                }
            } catch (Exception e) {
                log.error("ID={} 送审失败: {}", id, e.getMessage(), e);
            }
        });
        return R.ok();
    }
     **/


    @GetMapping("/createQRCode")
    public void createQRCode(@RequestParam String name, @RequestParam String appNo,HttpServletResponse response) {
        accessApplicationService.createQRCode(name, appNo, response);
    }
}
